package com.macy.mysok.activity;


import android.Manifest;
import android.app.Notification;
import android.app.NotificationManager;
import android.content.Context;
import android.content.pm.PackageManager;
import android.media.Ringtone;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.macy.mysok.R;
import com.macy.mysok.bean.Btc;
import com.macy.mysok.utils.BussinessWebSocketManager;
import com.macy.mysok.utils.FileSizeUtil;

import org.json.JSONObject;
import org.xutils.ex.DbException;
import org.xutils.view.annotation.ContentView;
import org.xutils.view.annotation.ViewInject;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.sql.Date;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.Random;


@ContentView(R.layout.activity_main)
public class MainActivity extends BaseActivity {

    private String URL="wss://bpp.moonsdsd.com/coingroup/ws/trade";
                      //wss://bpp.moonsdsd.com/coingroup/ws/trade

    //wss://bpp.moonsdsd.com/coingroup/ws/user/token // 用户信息

    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    private double myclose;//当前价格
    private Date mydate;// 最新时间

    Handler myHandler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 1:
                    show(msg.obj);
                    break;
            }
            super.handleMessage(msg);
        }
    };


    @ViewInject(R.id.date)
    TextView textViewdate;
    @ViewInject(R.id.text1)
    TextView textView1;
    @ViewInject(R.id.text2)
    TextView textView2;
    @ViewInject(R.id.text3)
    TextView textView3;
    @ViewInject(R.id.text4)
    TextView textView4;

    @ViewInject(R.id.ed1)
    EditText ed1;
    @ViewInject(R.id.ed2)
    EditText ed2;

    @ViewInject(R.id.but1)
    Button but1;
    @ViewInject(R.id.but2)
    Button but2;

    int miao=30;
    int max=30;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        if (Build.VERSION.SDK_INT >= 23) {
            int REQUEST_CODE_PERMISSION_STORAGE = 100;
            String[] permissions = {
                    Manifest.permission.READ_EXTERNAL_STORAGE,
                    Manifest.permission.WRITE_EXTERNAL_STORAGE
            };

            for (String str : permissions) {
                if (this.checkSelfPermission(str) != PackageManager.PERMISSION_GRANTED) {
                    this.requestPermissions(permissions, REQUEST_CODE_PERMISSION_STORAGE);
                    return;
                }
            }
        }


        Log.d("xxx","初始化");

        try {

            but1.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    try {
                        miao=Integer.valueOf(ed1.getText().toString());
                        max=Integer.valueOf(ed2.getText().toString());

                        but1.setEnabled(false);
                        ed1.setEnabled(false);
                        ed2.setEnabled(false);
                    } catch (Exception e) {
                        miao=30;
                        max=30;
                    }
                    BussinessWebSocketManager.getInstance()
                            .init(URL)
                            .setOnBussinessWebSocketListener(new BussinessWebSocketManager.OnBussinessWebSockeListener() {
                                @Override
                                public void onTestMessage(String text) {
                                    try {
                                        JSONObject my=new JSONObject(text);
                                        if(!my.has("candlestick")){
                                            Log.d("xxx","特别类型:"+text);return;
                                        }

                                        JSONObject jo=my.getJSONObject("candlestick");
                                        if(jo.has("symbol")&&jo.getString("symbol").equals("btcusdt")){
                                            Message message = new Message();
                                            message.what =1;
                                            message.obj=jo;
                                            myHandler.sendMessage(message);

                                            double close=jo.getDouble("close");// 最新价
                                            //Log.d("xxx","最新价:"+close+"");
                                        }

                                    }catch (Exception e){}
                                }
                            });

                }
            });
            but2.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    try {
                        app.db.delete(Btc.class);
                    } catch (DbException e) {}
                }
            });

            //copy(app.db.getDatabase().getPath(), getApplicationContext().getExternalCacheDir().getAbsolutePath()+"/macy.db");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }




    private void show(Object obj){
        JSONObject jo=(JSONObject)obj;

        try {
            double close=jo.getDouble("close");// 最新价
            double max=jo.getDouble("high");// 最大
            double min=jo.getDouble("low");// 最小
            Long timestamp=jo.getLong("timestamp");// timestamp
            myclose=close;
            mydate=new Date(timestamp);

            textView1.setText("最新价:"+close);

            textView2.setText("数据库大小:"+FileSizeUtil.getAutoFileOrFilesSize(app.db.getDatabase().getPath()));

            //Log.d("xxx",app.db.getDatabase().getPath());

            app.db.save(new Btc(close,max,min,sdf.format(mydate)));



            textViewdate.setText("moon send 时间:"+sdf.format(mydate));

            click();

        }catch (Exception e){}
    }

    /**
     * 检测 涨幅
     */
    private void click(){
        try {

            Calendar c = new GregorianCalendar();
            c.setTime(mydate);
            c.add(Calendar.SECOND,-miao);
            java.util.Date beforeDate=c.getTime();

            Btc btc=app.db.selector(Btc.class).where("timestamp",">=",sdf.format(beforeDate)).orderBy("timestamp",false).findFirst();
            if(null==btc||myclose<=0){
                return;
            }


            double zf=btc.getClose()-myclose;
            textView3.setText("与"+miao+"秒之前相差:"+String.format("%.2f", zf));
            textView4.setText("与"+miao+"秒之前涨幅:"+String.format("%.2f", zf));

            if(Math.abs(zf)>max){
                defaultMediaPlayer();
            }


        }catch (Exception e){
            Log.e("xxx",e.getMessage());
        }
    }




    private long exitTime = 0;
    public void defaultMediaPlayer() {
        try {
            if ((System.currentTimeMillis() - exitTime) > miao) {
                exitTime = System.currentTimeMillis();
                return;
            }

            Uri notification = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
            Ringtone r = RingtoneManager.getRingtone(this, notification);
            r.play();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    public static void copy(String source, String dest) {
        Log.d("aaa",source+"      "+dest);
        InputStream in = null;
        OutputStream out = null;
        try {
            in = new FileInputStream(new File(source));
            out = new FileOutputStream(new File(dest));

            byte[] buffer = new byte[1024];
            int len;

            while ((len = in.read(buffer)) > 0) {
                out.write(buffer, 0, len);
            }
            Log.d("aaa","完成了");
        } catch (Exception e) {
            Log.d("aaa",e.getMessage());
        } finally {
            try {
                in.close();
                out.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }




    /**
     *  accesstoken
     *
     * 做空
     * https://bpp.moonsdsd.com/coingroup/cointrade
     *{rate: 50, direction: "sell", inAmount: 100, duration: 25, tpPercent: 100, slPercent: 100,…}
     * direction: "sell" 做空=sell
     * duration: 25  固定
     * inAmount: 100 下注金额
     * rate: 50  杠杆
     * slPercent: 100  止盈
     * tpPercent: 100  止损
     * txCurrency: "btcusdt"
     */

}
